package com.kpmg.datalake.common.utils;

import com.kpmg.datalake.common.constants.WebConstants;
import com.kpmg.datalake.common.vo.UserDTO;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

/**
 * @author Alex.zhao [alex.zhao@kpmg.com]
 * @since Created on azhao6 on 2018-06-27 10:10:17
 */
public class ContextHolderUtils {


  /**
   * 设置国际化
   */
  public static SessionLocaleResolver resolver;


  private ContextHolderUtils() {

  }

  /**
   * SpringMvc下获取request
   *
   * @return HttpServletRequest
   */
  public static HttpServletRequest getRequest() {
    return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  }


  /**
   * SpringMvc下获取session
   *
   * @return HttpSession
   */
  public static HttpSession getSession() {
    return getRequest().getSession();
  }


  /**
   * Description: 获取当前登录用户
   *
   * @return UserDTO 返回类型
   */
  public static UserDTO getLoginUser() {
    return (UserDTO) getSession().getAttribute(WebConstants.SESSION_USER);
  }

  /**
   * 设置session 用户
   *
   * @param sysUser 用户信息
   */
  public static void setLoginUser(UserDTO sysUser) {
    getSession().setAttribute(WebConstants.SESSION_USER, sysUser);
  }

  /**
   * 获取当前系统的登陆名称
   *
   * @return String
   */
  public static String getUserName() {
    return (String) getSession().getAttribute(WebConstants.SESSION_USER_NAME);
  }

  /**
   * 设置当前session 用户名
   *
   * @param userName userName
   */
  public static void setUserName(String userName) {
    getSession().setAttribute(WebConstants.SESSION_USER_NAME, userName);
  }

  /**
   * 获取国际化方言
   *
   * @return 国际化方言
   */
  public static Locale getLocale() {
    HttpServletRequest request = ContextHolderUtils.getRequest();
    if (resolver == null) {
      resolver = SpringUtil.getBean(SessionLocaleResolver.class);
    }
    return resolver.resolveLocale(request);
  }

  public static SessionLocaleResolver getResolver() {
    return resolver;
  }

  /**
   * 设置会话方言
   *
   * @param resolver resolver
   */
  public static void setResolver(SessionLocaleResolver resolver) {
    ContextHolderUtils.resolver = resolver;
  }


}
